package com.uwantsoft.interfaces.web.controller.validator;

import com.uwantsoft.business.service.domain.user.User;
import com.uwantsoft.business.service.infrastructure.UserRepository;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author LeiPeichen.
 */
@Component(value = "userNameValidator")
public class UniqueUserNameValidator implements ConstraintValidator<UniqueUserName,String> {


    @Resource(name = "hibernateUserRepository")
    private UserRepository userRepository;

    @Override
    public void initialize(UniqueUserName username) {}
    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if(StringUtils.hasText(value)){
            String userName = value.trim();
            User user = userRepository.findByUsername(userName);
            if(user != null){
                return false;
            }
        }
        return true;
    }
}
